<template>
  <v-app>
    <v-main>
      <v-container>
        <v-card>
          <v-card-title> 用户列表 </v-card-title>

          <v-card-text>
            <v-text-field
              v-model="search"
              label="搜索姓名"
              @input="filterUsers"
              outlined
            ></v-text-field>
            <v-btn color="blue darken-1" @click="addUser">添加用户</v-btn>

            <v-table fixed-header height="50vh">
              <thead>
                <tr>
                  <th class="text-left">等级</th>
                  <th class="text-left">名称</th>
                  <th class="text-left">时间</th>
                  <th class="text-left">操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in filteredUsers" :key="item.name">
                  <td>
                    <span v-if="item.level === '1'">爬虫管理员</span>
                    <span v-else-if="item.level === '2'">高级爬虫</span>
                    <span v-else-if="item.level === '3'">中级爬虫</span>
                    <span v-else>初级爬虫</span>
                  </td>
                  <td>{{ item.username }}</td>
                  <td>{{ item.time }}</td>
                  <td>
                    <v-icon small tile @click="editUser(item)"
                      >mdi-pencil</v-icon
                    >
                    <v-icon small tile @click="deleteUser(item)"
                      >mdi-delete</v-icon
                    >
                  </td>
                </tr>
              </tbody>
            </v-table>
          </v-card-text>
        </v-card>

        <v-dialog v-model="dialog" max-width="500px">
          <v-card>
            <v-card-title>
              {{ formTitle }}
            </v-card-title>
            <v-card-text>
              <v-form ref="form" v-model="valid" @submit.prevent="saveUser">
                <v-text-field
                  v-model="editedUser.username"
                  label="用户名"
                  :rules="nameRules"
                ></v-text-field>
                <v-text-field
                  type="password"
                  v-if="oldPwdflog"
                  v-model="editedUser.oldpassword"
                  label="旧密码"
                  :rules="pwdRules"
                ></v-text-field>
                <v-text-field
                  type="password"
                  v-model="editedUser.password"
                  label="密码"
                  :rules="pwdRules"
                ></v-text-field>
                <v-select
                  label="等级"
                  v-model="selectedLevel"
                  :items="['初级爬虫', '中级爬虫', '高级爬虫', '爬虫管理员']"
                ></v-select>
              </v-form>
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="blue darken-1" text @click="closeDialog"
                >取消</v-btn
              >
              <v-btn
                color="blue darken-1"
                text
                @click="saveUser"
                :disabled="!valid"
                >保存</v-btn
              >
            </v-card-actions>
          </v-card>
        </v-dialog>

        <v-snackbar
          v-model="snackbar.show"
          :color="snackbar.color"
          :multi-line="snackbar.multiLine"
          :vertical="snackbar.vertical"
          :style="{ bottom: `90%` }"
        >
          {{ snackbar.text }}
        </v-snackbar>
      </v-container>
    </v-main>
  </v-app>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      selectedLevel: "初级爬虫",
      loading: false,
      search: "",
      users: [],
      dialog: false,
      oldPwdflog: false,
      valid: false,
      editedUser: {},
      snackbar: {
        show: false,
        text: "",
        color: "",
        multiLine: false,
        vertical: false,
      },
      nameRules: [
        (v) => !!v || "用户名必填项",
        (v) => (v && v.length <= 10) || "用户名不能超过10个字符",
      ],
      pwdRules: [
        (v) => !!v || "密码必填项",
        (v) => (v && v.length <= 100) || "密码不能超过100个字符",
      ],
      noDataText: "没有用户数据",
    };
  },
  computed: {
    filteredUsers() {
      // 如果搜索关键字为空，则返回所有用户
      if (this.search === "") {
        return this.users;
      }

      // 使用过滤逻辑，根据姓名进行搜索
      const searchValue = this.search.toLowerCase();
      return this.users.filter((user) => {
        const fullName = `${user.username} ${user.level}`.toLowerCase();
        return fullName.includes(searchValue);
      });
    },
  },
  methods: {
    editUser(user) {
      this.editedUser = { ...user };
      this.oldPwdflog = true;
      this.dialog = true;
    },
    deleteUser(user) {
      this.sendAxios("/api/user/delete", { ...user });
      this.userinfo();
    },
    saveUser() {
      this.oldPwdflog = false;
      this.$refs.form.validate().then((valid) => {
        if (valid) {
          // 添加用户
          let level = 4;
          if (this.selectedLevel === "初级爬虫") {
            level = 4;
          }
          if (this.selectedLevel === "中级爬虫") {
            level = 3;
          }
          if (this.selectedLevel === "高级爬虫") {
            level = 2;
          }
          if (this.selectedLevel === "爬虫管理员") {
            level = 1;
          }
          if (this.isNewUser) {
            this.sendAxios("/api/register", {
              username: this.editedUser.username,
              password: this.editedUser.password,
              level: level,
            });
          } else {
            // 编辑用户
            const index = this.users.findIndex(
              (u) => u.id === this.editedUser.id
            );
            if (index > -1) {
              this.users[index] = { ...this.editedUser };
              this.editedUser.level = level;
              this.sendAxios("/api/user/update", { ...this.editedUser });
              this.showSnackbar("用户已更新", "success");
            }
          }
          this.dialog = false;
          this.isNewUser = false; // 重置isNewUser状态
          this.userinfo();
          this.editedUser = {};
        }
      });
    },
    closeDialog() {
      this.oldPwdflog = false;
      this.isNewUser = false;
      this.dialog = false;
      this.editedUser = {};
    },
    sendAxios(url, data) {
      axios
        .post(url, data)
        // 发送GET请求到后端API
        .then((response) => {
          this.showSnackbar(response.data.msg, "success");
        })
        .catch((error) => {
          // 处理请求错误
          this.showSnackbar(error.response.data.msg, "error");
        });
    },
    showSnackbar(text, color) {
      this.snackbar.text = text;
      this.snackbar.color = color;
      this.snackbar.show = true;
    },
    filterUsers() {
      // 仅仅通过更新搜索关键字，Computed属性 filteredUsers 会自动更新表格数据
      // 没必要在这里做额外的操作
    },
    addUser() {
      this.valid = false;
      this.isNewUser = true;
      this.dialog = true;
    },
    userinfo() {
      axios
        .get("/api/user/list") // 发送GET请求到后端API
        .then((response) => {
          this.users = response.data.data;
          console.log(this.users);
        })
        .catch((error) => {
          // 处理请求错误
          this.showSnackbar(error.response.data.msg, "error");
        });
    },
  },
  created() {
    this.userinfo();
  },
};
</script>
